//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_testcase_api_serv

import (
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/testcase_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_testcase_api"
)

type ProjectTestCaseApiImpl struct {
	project_testcase_api.UnimplementedProjectTestCaseApiServer
}

func (apiImpl *ProjectTestCaseApiImpl) calcFolderPerm(sessionItem *dao.SessionDbItem, projectItem *project_dao.ProjectInfoDbItem, roleItem *project_dao.RoleInfoDbItem, folderInfo *testcase_dao.FolderInfoDbItem) *project_testcase_api.UserPerm {
	retPerm := &project_testcase_api.UserPerm{}

	if sessionItem.UserId == projectItem.OwnerUserId || roleItem.BasicInfo.Admin {
		retPerm.CanUpdate = true
		if folderInfo.SubCaseCount == 0 && folderInfo.SubFolderCount == 0 {
			retPerm.CanRemove = true
		}
	} else if folderInfo.PermSetting.UpdateForAll {
		retPerm.CanUpdate = true
		if folderInfo.SubCaseCount == 0 && folderInfo.SubFolderCount == 0 {
			retPerm.CanRemove = true
		}
	} else {
		for _, userId := range folderInfo.PermSetting.ExtraUpdateUserIdList {
			if userId == sessionItem.UserId {
				retPerm.CanUpdate = true
				if folderInfo.SubCaseCount == 0 && folderInfo.SubFolderCount == 0 {
					retPerm.CanRemove = true
				}
			}
		}
	}
	return retPerm
}

func (apiImpl *ProjectTestCaseApiImpl) calcCasePerm(sessionItem *dao.SessionDbItem, projectItem *project_dao.ProjectInfoDbItem, roleItem *project_dao.RoleInfoDbItem, caseInfo *testcase_dao.CaseInfoDbItem) *project_testcase_api.UserPerm {
	retPerm := &project_testcase_api.UserPerm{}

	if sessionItem.UserId == projectItem.OwnerUserId || roleItem.BasicInfo.Admin {
		retPerm.CanUpdate = true
		retPerm.CanRemove = true

	} else if caseInfo.PermSetting.UpdateForAll {
		retPerm.CanUpdate = true
		retPerm.CanRemove = true
	} else {
		for _, userId := range caseInfo.PermSetting.ExtraUpdateUserIdList {
			if userId == sessionItem.UserId {
				retPerm.CanUpdate = true
				retPerm.CanRemove = true
			}
		}
	}
	return retPerm
}
